var express = require('express');
var router = express.Router();

let User = require('../models/user')
const userId = '10001'
// 获取信息
router.get('/getMessage', (req, res, next) => {

  User.findOne({userId: userId}, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (doc) {
        res.json({
          result: doc
        })
      }
    }
  })
})

// 写入信息
router.post('/add', (req, res, next) => {
  let caseName = req.body.caseName;
  let detail = req.body.detail;
  let time = (new Date()).getTime();
  console.log(caseName)
  console.log(detail)
  User.findOne({'userId': userId}, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      let message = {
        caseId: Math.ceil(Math.random()*10000),
        caseName: caseName,
        detail: detail,
        isRead: false,
      }
      doc.messages.push(message)
      doc.save((err1, doc1) => {
        if (err1) {
          res.json({
            status: '1',
            msg: err1.message,
            result: ''
          })
        } else {
          res.json({
            status: '0',
            msg: '',
            result: '写入成功'
          })
        }
      })
    }
  })
})

// 更新信息
router.post('/update', (req, res, next) =>{
  const caseId = req.body.caseId;
  const isRead = req.body.isRead;
  User.update({'userId': userId,'messages.caseId':caseId}, {'messages.$.isRead':isRead}, (err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: '更新成功'
      })
    }
  })
})

module.exports = router;